var maplet = null;
$(document).ready(function () {
    initMap();
    initMessage();
    bindEvent();
});

function bindEvent() {
    $('#clear').click(function () {
        maplet.clearOverlays();
        maplet.setMode("drawarea", onDrawarea)
    });
}

function initMap() {
    maplet = new Maplet("mmap");
    maplet.centerAndZoom(new MPoint(0, 0), 0);

    document.getElementById('LayerScale').style.display = 'none';
    document.getElementById('ImgCopyright').style.display = 'none';

    maplet.setMode("drawarea", onDrawarea)
    onWindowResize();
}

function initMessage() {
    $("#mmap").mousemove(function (a) {
        var b = a.pageX, c = a.pageY;
        $("#message").css({top: c + 15, left: b + 10})
    }).mouseover(function () {
        $("#message").show();
        var polylines = maplet.getPolylines();
        if (null == polylines || 0 == polylines.length) {
            $("#message").html("在地图上点击鼠标左键绘制区域，双击结束");
        } else {
            $("#message").html("如果您想重绘区域，点击清除区域按钮后重新在地图上绘制区域");
        }
    }).mouseout(function () {
        $("#message").hide()
    })
}

function onWindowResize() {
    $('#clear').css("left", $('#mmap').position().left);
    $('#clear').css("top", $('#mmap').position().top);
}

function onDrawarea(ob) {
    var brush = new MBrush("green");
    brush.arrow = false;
    brush.style = 0;
    brush.stroke = 1;
    brush.fill = true;
    brush.bgcolor = "blue";
    brush.color = "red";
    brush.bgtransparency = 35;
    var polyline = new MPolyline(
        ob.points,
        brush
    );
    maplet.addOverlay(polyline);
}

function checkPolyline(polylines) {
    if (polylines == null || polylines.length != 1 || polylines[0].pts == null || polylines[0].pts.split(';').length < 3) {
        $.messager.show({style: {right: '', top: document.body.scrollTop + document.documentElement.scrollTop, bottom: ''}, showType: 'slide',
            title: '错误提示',
            msg: '地图上必须定义一个至少包含三个点的区域（仅一个）！',
            timeout: 5000,
            showType: 'slide'
        });
        return false;
    }

    var pts = polylines[0].pts + ";" + polylines[0].pts.split(";")[0];

    var pts = "POLYGON((" + pts.replaceAll(",", " ").replaceAll(";", ",") + "))";
    $('#fence_polylinePts').val(pts);
    return true;
}